package com.cutthroatcreations.woodenrailway;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class TrainsProvider extends ContentProvider {

	SQLiteDatabase db;

	// All Static variables

	private static final String TAG = "DatabaseHandlerLog";

	// Database Version
	private static final int DATABASE_VERSION = 1;

	// Database Name
	public static final String DATABASE_NAME = "trainsManager";

	// Table names
	public static final String TABLE_TRAINS = "trains";

	// Table Column names
	public static final String KEY_ID = "id";
	public static final String KEY_NAME = "name";
	public static final String KEY_IT_NO = "item_number";
	public static final String KEY_SYN = "synopsis";
	public static final String KEY_IMG = "image_name";

	// Table Column Numbers
	public static final int ID_COLUMN = 0;
	public static final int NAME_COLUMN = 1;
	public static final int IT_NO_COLUMN = 2;
	public static final int SYN_COLUMN = 3;
	public static final int IMG_COLUMN = 4;

	// Content provider constants
	private static final String AUTH = "com.cutthroatcreations.woodenrailway.TrainsProvider";
	public static final Uri TRAINS_URI = Uri.parse("content://" + AUTH + "/"
			+ TABLE_TRAINS);

	// Uri variables
	private static final int ALL_TRAINS = 1;
	private static final int ONE_TRAIN = 2;

	// Uri Matcher variable with implementation
	private static final UriMatcher uriMatcher;
	static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

		uriMatcher.addURI("com.cutthroatcreations.woodenrailway", TABLE_TRAINS,
				ALL_TRAINS);

		uriMatcher.addURI("com.cutthroatcreations.woodenrailway", TABLE_TRAINS
				+ "/#", ONE_TRAIN);
	}

	public static class trainDbHelper extends SQLiteOpenHelper {

		private static final String CREATE_TRAINS_TABLE = "CREATE TABLE "
				+ TABLE_TRAINS + "(" + KEY_ID + " INTEGER PRIMARY KEY, "
				+ KEY_NAME + " VARCHAR(100), " + KEY_IT_NO + " VARCHAR(5), "
				+ KEY_SYN + " TEXT, " + KEY_IMG + " VARCHAR(255) " + ")";

		public trainDbHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);

		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(CREATE_TRAINS_TABLE);

		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

			Log.v(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all data.");
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_TRAINS);

		}
	}

	@Override
	public boolean onCreate() {

		Context context = getContext();
		trainDbHelper dbHelper = new trainDbHelper(context, DATABASE_NAME,
				null, DATABASE_VERSION);
		db = dbHelper.getWritableDatabase();
		return (db == null) ? false : true;

	}

	@Override
	public String getType(Uri uri) {

		switch (uriMatcher.match(uri)) {

		case ALL_TRAINS:
			return "vnd.android.cursor.dir/vnd.cutthroatcreations.woodenrailway";

		case ONE_TRAIN:
			return "vnd.android.cursor.item/vnd.cutthroatcreations.woodenrailway";
		default:
			throw new IllegalArgumentException("Unsupported URI: " + uri);

		}
	}

	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		int count;
		try{
		count = db.delete(TABLE_TRAINS,
				KEY_ID + "=" + where , null);
		return count;
		}catch(SQLiteException e){
			e.printStackTrace();
		}
		//getContext().getContentResolver().notifyChange(uri, null);
		return 0;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		long rowID = db.insert(TABLE_TRAINS, null, values);

		if (rowID > 0) {
			getContext().getContentResolver().notifyChange(uri, null);
			return uri;
		}
		throw new SQLException("Failed to insert row into " + uri);

	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {

		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables(TABLE_TRAINS);

		switch (uriMatcher.match(uri)) {

		case ONE_TRAIN: {

			qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1));
			break;
		}
		default:
			break;
		}
		String orderBy;
		if (TextUtils.isEmpty(sortOrder)) {
			orderBy = KEY_ID;
		} else {
			orderBy = sortOrder;
		}

		Cursor c = qb.query(db, projection, selection, selectionArgs, null,
				null, orderBy);

		c.setNotificationUri(getContext().getContentResolver(), uri);

		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where,
			String[] whereArgs) {

		int count;

		switch (uriMatcher.match(uri)) {
		case ALL_TRAINS:
			count = db.update(TABLE_TRAINS, values, where, whereArgs);
			break;
		case ONE_TRAIN:
			String segment = uri.getPathSegments().get(1);
			count = db.delete(TABLE_TRAINS,
					KEY_ID
							+ "="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ")" : ""), whereArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI: " + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

}
